/*
 * Copyright © OpenAtom Foundation.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package io.iec.edp.caf.msu.client.discovery;

import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import io.iec.edp.caf.commons.runtime.CafEnvironment;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.commons.utils.StringUtils;
import io.iec.edp.caf.msu.api.client.ServiceDiscovery;
import io.iec.edp.caf.msu.api.entity.MsuProperties;
import io.iec.edp.caf.msu.api.server.MsuServiceDiscovery;
import io.iec.edp.caf.msu.client.exception.ServiceNotFoundException;
import io.iec.edp.caf.msu.client.exception.ServiceUnitNotFoundException;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author Leon Huo
 */
@Slf4j
public class NacosDiscoveryImpl implements ServiceDiscovery {

    private NamingService namingService;
    private MsuProperties configuration;
    private boolean enableSSL = false;
    private final Logger logger = LoggerFactory.getLogger(NacosDiscoveryImpl.class);

    public NacosDiscoveryImpl(NamingService namingService, MsuProperties configuration) {
        this.namingService = namingService;
        this.configuration=configuration;
        this.enableSSL = this.enableSSL();
    }

    @Override
    public String discover(String serviceUnitName, HashMap<String, String> eventContext) {
        serviceUnitName = serviceUnitName.toLowerCase();
        var address = discoverByNacos(serviceUnitName);
//        if(address==null || address.length()==0){
//            address = disconverByNacosAndDb(serviceUnitName,eventContext);
//        }
        return address;
    }

    @Override
    public List<String> discoverAll(String serviceUnitName, HashMap<String, String> eventContext) {
        List<String> addresses = discoverAllByNacos(serviceUnitName);

        // todo: if needs dicoverAllFromDb when getting nothing from Nacos
        return addresses;
    }

    private String discoverByNacos(String serviceUnitName){

        logger.info("nacos discover:start found service by su"+serviceUnitName+"");
        String address;
        Instance instance=null;
        var check = true;
        try {
            instance = namingService.selectOneHealthyInstance(serviceUnitName);
            logger.info("nacos discover:current service instance ip:"+instance.getIp());
        } catch (Exception e) {
            check = false;
            log.error("nacos discover:can not found service by su："+serviceUnitName,e);
        }finally {
            if(check && instance!=null){
                address = instance.getIp() + ':' + instance.getPort();
                return this.enableSSL? "https://" + address:"http://" + address;
            }else{
                throw new ServiceUnitNotFoundException("nacos discover: current su: "+serviceUnitName+" is not available，can not found service by su:"+serviceUnitName);
            }

        }

//        return getAddressFromNacos(serviceUnitName);
    }

    private List<String> discoverAllByNacos(String serviceUnitName){
        logger.info("nacos:即将通过serviceUnitName "+serviceUnitName+"去nacos里发现服务地址");
        List<Instance> instances = null;
        List<String> addresses = new ArrayList<>();
        //var check = true;
        try {
            instances = namingService.getAllInstances(serviceUnitName);
            for(Instance instance:instances){
                String address = instance.getIp()+ ':' + instance.getPort();
                address = this.enableSSL? "https://" + address : "http://" + address;
                addresses.add(address);
            }
            logger.info("nacos:获取的所有ip:"+addresses);
        } catch (Exception e) {
            //check = false;
            log.error("通过服务名："+serviceUnitName+"未在nacos里找到对应的服务"+e.getMessage(),e);
        }finally {
            return addresses;
        }
    }

    private String disconverByNacosAndDb(String serviceUnitName, HashMap<String, String> eventContext){
        serviceUnitName = serviceUnitName.toLowerCase();
        String appName = configuration.getApplicationName();
        LinkedHashMap<String, Object> paramMap = new LinkedHashMap<>();
        paramMap.put("appName", appName);
        paramMap.put("serviceUnitName", serviceUnitName);

        logger.info("nacos:即将通过AppName:"+appName+"Su:"+serviceUnitName+"去msuregisterinfo表找servicename");

        MsuServiceDiscovery msuServiceDiscovery = SpringBeanUtils.getBean(MsuServiceDiscovery.class);
        String serviceName = msuServiceDiscovery.discover(appName,serviceUnitName);

        if (serviceName == null) {
            logger.info("nacos:通过AppName: {} 和 Su: {}没要找到对应的servicename", appName,serviceUnitName);
            var msg = new StringBuilder();
            msg.append("nacos路由:排查建议:");
            msg.append("1.检查nacos里是否有对应的su:"+serviceUnitName);
            msg.append("2.检查nacos里对应的MicroServiceUnit服务对应的应用服务器是否连接到主库");
            msg.append("3.检查主库的gspmsuregisterinfo表当前appname:"+appName+"和serviceunitname:"+serviceUnitName+"的数据是否存在");
            msg.append("4.若以上都没有，证明当前su没有启用，请检查系统盘里是否有\"+serviceUnitName+\"所对应的ServiceUnit.json配置");
            msg.append("5.若以上都没有，检查server/config/runtime/caf_serviceunits.json文件里该su是否禁用（enable=false）或者配置了该su的黑名单（strategy：BlackList）");
            throw new ServiceUnitNotFoundException("当前su:"+serviceUnitName+"不可用，通过AppName:"+appName+"和SU:"+serviceUnitName+"没有获取到nacos的服务名。"+msg.toString());
//            throw new RuntimeException("当前远程调用RPC时,通过AppName:"+appName+"和SU:"+serviceUnitName+"没有获取到nacos的服务名。"+msg.toString());
        }

        logger.info("nacos:当前远程调用RPC时的服务名: {}，Su: {}", serviceName, serviceUnitName);
        return getAddressFromNacos(serviceName);
    }

    /**
     * 通过服务名获取地址
     * @param serviceName 服务名 SuName
     * @return
     */
    private String getAddressFromNacos(String serviceName) {
        String address;
        Instance instance;
        try {
            instance = namingService.selectOneHealthyInstance(serviceName);
            logger.info("nacos: current ip:"+instance.getIp());
        } catch (Exception e) {
//            throw new RuntimeException("通过服务名："+serviceName+"未在nacos里找到对应的服务",e);
            throw new ServiceNotFoundException("current service "+serviceName+" not avaible，"+serviceName+"can not found service in nacos");
        }

        address = instance.getIp() + ':' + instance.getPort();
        return this.enableSSL? "https://" + address:"http://" + address;
    }

    /**
     * @return 是否开启https
     */
    private boolean enableSSL() {
        Environment environment = CafEnvironment.getEnvironment();
        return !StringUtils.isEmpty(environment.getProperty("server.ssl.key-store"));
    }
}
